package com.gjd.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.gjd.domain.ResponseResult;
import com.gjd.domain.entity.Category;
import com.gjd.domain.vo.ExcelCategoryVo;
import com.gjd.domain.vo.enums.AppHttpCodeEnum;
import com.gjd.service.CategoryService;
import com.gjd.utils.BeanCopyUtils;
import com.gjd.utils.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/admin/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @GetMapping("/categoryListPage")
    public ResponseResult categoryListPage(Long pageNum, Long pageSize) {
        return categoryService.getCategoryListPage(pageNum, pageSize);
    }

    @PostMapping("/addCategory")
    public ResponseResult addCategory(@RequestBody Category category) {
        return categoryService.addCategory(category);
    }

    @PutMapping("/updateCategory")
    public ResponseResult updateCategory(@RequestBody Category category) {
        return categoryService.updateCategory(category);
    }

    @PostMapping("/deleteCategory")
    public ResponseResult deleteCategory(Long categoryId) {
        return categoryService.deleteCategory(categoryId);
    }

    @GetMapping("/exportCategory")
    public void exportCategoryToExcel(HttpServletResponse response) throws IOException {
        try {
//        设置下载文件的请求头
            WebUtils.setDownLoadHeader("分类表.xlsx", response);
//        获取需要导出的数据
            List<Category> categoryList = categoryService.list();
            List<ExcelCategoryVo> excelCategoryVoList = BeanCopyUtils.copyBeanList(categoryList, ExcelCategoryVo.class);
//        把数据写入excel中
            EasyExcel.write(response.getOutputStream(), ExcelCategoryVo.class).autoCloseStream(Boolean.FALSE).sheet("分类导出表")
                    .doWrite(excelCategoryVoList);
        } catch (Exception e) {
//        出现异常把异常信息写入响应当中
            ResponseResult responseResult = ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR);
            WebUtils.renderString(response, JSON.toJSONString(responseResult));
        }
    }
}
